package nl.hanze.designpatterns.gui;

import java.awt.BorderLayout;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import nl.hanze.designpatterns.domain.Answer;

import nl.hanze.designpatterns.domain.Question;
import nl.hanze.designpatterns.io.FAQBuilder;

public class FaqPanel extends JPanel {

	//private ArrayList<Question> questions;
	
	private static final long serialVersionUID = 3302392823019362428L;
	private int i;
	private final FAQBuilder faqBuilder;
	private final ArrayList<Question> questions;
	
	public FaqPanel(){
		super();		
		faqBuilder = new FAQBuilder();
		questions = faqBuilder.getRootQuestions();
		buildPanel();
	}

	public void buildPanel(){
		
		this.setLayout(new BorderLayout());
		JLabel faqtext = new JLabel("Welcome to the FAQ Panel. Please choose a question");
		this.add(faqtext, BorderLayout.NORTH);
		
		JPanel listpanel = new JPanel();
		
		
		
		for(i = 0; i < questions.size(); i++){
			JButton button = new JButton(questions.get(i).getDescription());
			button.addActionListener(new ActionListener(){ // een button aanmaken voor elke rootquestion, zodat als je er op drukt het antwoord te zien krijgt in een schermpje
				public void actionPerformed(ActionEvent e){
					openAnswers(questions.get(i-1));
				}
			});
			listpanel.add(button);
		}
			this.add(listpanel, BorderLayout.CENTER);
		
	}
	
	
	
	public void openAnswers(Question question){
		
		final ArrayList<Answer> answers = faqBuilder.getAnswers(question);
				
		
		JFrame frame = new JFrame();
		JPanel panel = new JPanel();
		frame.getContentPane().add(panel);	
		Box box = Box.createVerticalBox();	
		JLabel label = new JLabel(question.getQuestion());
		box.add(label);
		
		;
		
		for(int i = 0; i < answers.size(); i++){
			JButton temp = new JButton(answers.get(i).getAnswer());
			temp.addActionListener(new ActionListener(){

				@Override
				public void actionPerformed(ActionEvent e) {
					JButton temp = (JButton) e.getSource();
					String answer = temp.getText();					
					openQuestion(answers, answer);
			}
			}
			);
			box.add(temp);
		}
		
		panel.add(box);
		frame.setSize(300, 200);
		frame.setResizable(false);
		frame.setLocationRelativeTo(null);
		frame.setVisible(true);
		
			
		
	}
	
	public void openQuestion(ArrayList<Answer> answers, String answer){
		
		Answer a = null;
		for(int i = 0; i < answers.size(); i++){
			
			if(answers.get(i).getAnswer().equals(answer))
				a = answers.get(i);
		}
		
		if(a != null){
			Question q = a.getQuestion();
			if(q != null)
				openAnswers(q);
		}
			
	}

	
	

}
